//
//  BaseEntity.m
//  LotteryClient
//
//  Created by SunYu on 14-2-6.
//  Copyright (c) 2014年 SunYu. All rights reserved.
//

#import "BaseEntity.h"
#import "JSONKit.h"
#import "BaseCacheManager+NSCoding.h"
#import "BaseCacheManager+UserDefaults.h"
#import "NSString+BaseFramework.h"
#import "NSMutableDictionary+BaseFramework.h"
@interface BaseEntity ()


/**
 *  在此方法中做名称转换，类中属性名称与json或dic中的Key值转换
 *
 *
 *  @param sourceName json或者dic中的key
 *
 *  @return 返回对应的属性名称
 */
- (NSString *)nameBySourceName:(NSString *)sourceName;

- (Class)objectTypeInJsonArrayWityArrayName:(NSString *)arrayName;
@end

@implementation BaseEntity
DEF_STATIC_PROPERTY_INT(baseType, BaseTypeEntity )

- (id)init
{
	if (self = [super init])
	{
		_propertyNameAndTypeDic = [NSMutableDictionary dictionary];

		Class cla = [self class];
		while (cla != [BaseEntity class])
		{
			NSDictionary *dic = [cla getPropertyNameAndTypeDic];
			
			[_propertyNameAndTypeDic addEntriesFromDictionary:dic];
			cla = [cla superclass];
			
		}
		
		return self;
	}

	return nil;
}
- (id)initWithSourceString:(id)sourceString
{
	if (self = [self init])
	{
		[self resetAllVarsByContent:sourceString];
		return self;
	}

	return nil;
}

- (NSString *)sourceString
{
	return _sourceString;
}

- (void)setSourceString:(id)sourceString
{
	[self resetAllVarsByContent:sourceString];
}

- (void)resetAllVarsByContent:(id)content
{
	NSDictionary *userInfoDic = nil;
	if (_sourceString)
	{
    }

	if([content isKindOfClass:[NSDictionary class]])
	{
		_sourceString = [[NSString alloc] initWithString:[content JSONString]];
		userInfoDic = content;
	}
	else
	{
		_sourceString = [[NSString alloc] initWithString:content];
		userInfoDic = [_sourceString objectFromJSONString];
	}

	if ([_sourceString length] >0)
	{

		NSArray *keys = [userInfoDic allKeys];

        BaseEntity *entity = nil;

        for (NSString *key in keys)
		{
			id value = [userInfoDic objectForKey:key];
			if (value)
			{
				NSString *name = [self nameBySourceName:key];
				NSString *type = [_propertyNameAndTypeDic objectForKey:name];

				if (type && [type length] > 0 )
				{
					Class clazz = NSClassFromString(type);
					if ([clazz isSubclassOfClass:[BaseEntity class]])
					{
						entity = [[clazz alloc] initWithSourceString:value];
						value = entity;
					}
					else if ([clazz isSubclassOfClass:[NSArray class]] &&
							 [value isKindOfClass:clazz])
					{
						if ((clazz = [self objectTypeInJsonArrayWityArrayName:name]))
						{
							NSMutableArray *array = [NSMutableArray array];
							
							for (NSDictionary *dic in value)
							{
								if ([dic isKindOfClass:[NSDictionary class]])
								{
                                    [array addObject:[[clazz alloc] initWithSourceString:dic]];
								}
							}
							
							value = array;
						}
					}
					else 
					{
						
						//如果属性为字符串 json数据为 nsnumber 时 转换
						if ([value class] != clazz  && (clazz == [NSString class]) )
						{
							value = [NSString stringWithFormat:@"%@",value];
						}
						
						if ([type isEqualToString:NSStringFromClass([NSDate class])])
						{
							value = [value getFormatterDate];
						}
					}
					
					
				}
				[self setValue:value forKey:name];
			}


		}
	}

}





- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
//	DLog(@"UndefinedKey :%@",key);

}

- (void)dealloc
{
}


- (void)copyPropertyValueFromObject:(id)object
{
	NSDictionary *nameAndValueDic = [object getPropertyNameAndValue];
	NSArray *names = [nameAndValueDic allKeys];
	for (NSString *name in names)
	{
		id value = [nameAndValueDic objectForKey:name];
		if (value)
		{
			[self setValue:value forKey:name];
		}
	}
}


- (NSString *)nameBySourceName:(NSString *)sourceName
{
	NSString *result = [[self nameSwitchDictionary] objectForKey:sourceName];
	return result ? result : sourceName;
}

- (NSDictionary *)nameSwitchDictionary
{
	return [NSDictionary dictionaryWithObjectsAndKeys:nil];
}


- (Class)objectTypeInJsonArrayWityArrayName:(NSString *)arrayName
{
	Class clazz = [[self objectTypeInJsonArrayDictionary] objectForKey:arrayName];

	return clazz;
}

- (NSDictionary *)objectTypeInJsonArrayDictionary
{
	return [NSDictionary dictionaryWithObjectsAndKeys:nil];

}
- (NSDictionary *)dictionaryForJson
{
	return nil;
}

- (void)saveToFileWithFileName:(NSString *)fileName withPath:(NSString *)path
{
    if (fileName && [fileName notEmpty])
    {
		
        if ([self conformsToProtocol:@protocol(NSCoding)])
        {
            if (!path ||![path notEmpty])
            {
                path = [[BaseCacheManager userDocumentPath] copy];
            }
            [BaseCacheManager saveObject:self
                                  toFile:fileName
                               storePath:path];
        }
        
    }
}


- (void)saveToUserDefaultForKey:(NSString *)key
{
	
    if ([self conformsToProtocol:@protocol(NSCoding)])
    {
        [BaseCacheManager setInUserDefaultsObject:self forKey:key];
    }

    
}


+ (instancetype)loadObjectFromFileWithFileName:(NSString *)fileName withPath:(NSString *)path
{
    if (fileName && [fileName notEmpty])
    {
		if (!path ||![path notEmpty])
		{
			path = [BaseCacheManager userDocumentPath];;
		}
		
        return [BaseCacheManager loadObjectFromFile:fileName storePath:path];
    }
    else
    {
        return nil;
    }
}

+ (instancetype)loadObjectFromUserDefaultWithKey:(NSString *)key

{
    if (key && [key notEmpty])
    {
        return [BaseCacheManager objectInUserDefaultsForKey:key];
    }
    else
    {
        return nil;
    }
}

- (id)initWithCoder:(NSCoder *)coder
{
    self = [self init];
    if (self)
    {
        _sourceString           = [[coder decodeObjectForKey:@"_sourceString"] copy];
		[self resetAllVarsByContent:_sourceString];
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:self.sourceString
                 forKey:@"_sourceString"];

}

- (NSDictionary *)dictionaryWithNameAndValue
{
	

	NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
	NSMutableDictionary *tempDictionary = [NSMutableDictionary dictionary];

	Class cla = [self class];
	while (cla != [BaseEntity class])
	{
		NSDictionary *dic = [cla getPropertyNameAndTypeDic];
		
		[tempDictionary addEntriesFromDictionary:dic];
		cla = [cla superclass];
		
	}
	
	
	NSArray *allKeys = [tempDictionary allKeys];
	for (NSString *key in allKeys)
	{
		NSString *switchKey = [[self dictionaryForJson] objectForKey:key];
		id value = [self valueForKey:key];
		
		if (CHECK_VALID_STRING(switchKey))
		{
			[dictionary setSafeObject:value forKey:switchKey];
		}
		else
		{
			[dictionary setSafeObject:value forKey:key];
		}
	}
	

	
	return dictionary;
}

- (NSString *)description
{
	NSMutableString *desc = [NSMutableString string];
	[desc appendFormat:@"%p \n",self];
	[desc appendFormat:@"%@",[self dictionaryWithNameAndValue] ];
	
	
	return desc;
	
}


@end
